//
//  HICComposePictureView.swift
//  vibo
//
//  Created by jht-seven on 16/7/3.
//  Copyright © 2016年 jht-seven. All rights reserved.
//

import UIKit

//cell 重用标识符
private let pictureViewCellId = "pictureViewCellId"

class HICComposePictureView: UICollectionView {
    //告知外界弹出相册
    var composePictureViewClosure: (()->())?
    
    // 保存image的数组
    var imageList:[UIImage] = [UIImage]()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 共外界调用的方法
    func addImages(image: UIImage){
        imageList.insert(image, atIndex: 0)
        //如果count大于9 删除最后一张图片
        if imageList.count > 9 {
            imageList.removeLast()
        }
        
        //刷新数据
        reloadData()
    }
    
    //MARK: - 设置视图
    private func setupUI(){
        //首次进入想把当前配图隐藏
        hidden = true
        
        backgroundColor = UIColor.whiteColor()
        //        // 注册cell
        registerClass(HICComposePictureViewCell.self, forCellWithReuseIdentifier: pictureViewCellId)
        dataSource = self
        delegate = self
        // 设置layout
        let layout =  collectionViewLayout as! UICollectionViewFlowLayout
        let itemMargin: CGFloat = 5
        let cellWH = (SCREENW - 20 - itemMargin*2)/3
        // 设置item
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
        // 设置垂直和水平间距
        layout.minimumInteritemSpacing = itemMargin
        layout.minimumLineSpacing = itemMargin
    }
    
    
}

extension HICComposePictureView: UICollectionViewDataSource,UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let count = imageList.count
        if count == 0 || count == 9 {
            return count
        }else {
            return imageList.count + 1
        }
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureViewCellId, forIndexPath: indexPath) as! HICComposePictureViewCell
        
        if imageList.count == indexPath.item {
            cell.image = nil
        }else{
            cell.image = imageList[indexPath.item]
        }
        
        //实现闭包
        cell.deleteButtonClosure = {
            //删除数组指定元素
            self.imageList.removeAtIndex(indexPath.item)
            //如果count = 0 隐藏配图
            if self.imageList.count == 0 {
                self.hidden = true
            }
            //刷新Ui
            self.reloadData()
        }
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        collectionView.deselectItemAtIndexPath(indexPath, animated: true)
        //如果数组的count == indexPath.item 就是加号按钮
        if imageList.count == indexPath.item {
//            print("加号按钮")
            composePictureViewClosure?()
        }
    }
    
    
    
}



// 自定义cell
class HICComposePictureViewCell: UICollectionViewCell{
    //声明删除按钮闭包
    var deleteButtonClosure: (()->())?
    //共外界给其赋值
    var image:UIImage?{
        didSet{
            //要设置加号按钮
            if image == nil{
                bgImageView.image = UIImage(named: "compose_pic_add")
                bgImageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
            }else{
                //正常显示
                bgImageView.image = image
                //解决cell重用问题
                bgImageView.highlightedImage = nil
                //显示删除按钮
                deleteButton.hidden = false
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 监听事件
    @objc private func deleteButtonClick(){
        deleteButtonClosure?()
    }
    
    
    // MARK: - 设置视图
    private func setupUI(){
        
        backgroundColor = UIColor.whiteColor()
        //添加控件
        contentView.addSubview(bgImageView)
        //添加约束
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
    }
    
    // MARK: - 懒加载控件
    private lazy var bgImageView: UIImageView = UIImageView()
    // 删除按钮
    private lazy var deleteButton: UIButton = {
        let button = UIButton()
        //添加点击事件
        button.addTarget(self, action: "deleteButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        
        return button
    }()
}




